package com.ftg.learn.day10.exam;

import lombok.Data;

import java.time.LocalDateTime;

/**
 * 用户
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/8/9 下午2:12
 */
@Data
public class User {
    private String name;

    //。。。。

    private int index = 0;

    private volatile Book[] books;

    public User(String name) {
        this.name = name;
        books = new Book[6];
    }

    /**
     * 借书
     */
    public synchronized void lendBook(Book book) {

        // 容错
        if (book.getCount() == 0) {
            throw new RuntimeException("没有了");
        }

        if (this.index == books.length) {
            throw new RuntimeException("先看你错到的吧");
        }

        // books 多一个
        this.books[this.index++] = book;

        //book  count --
        book.deIncrCount();
    }

    public synchronized void returnBook(int index) {
        if (index < 0 || index > this.index || this.index == 0) {
            throw new RuntimeException("请正确还书");
        }

        //要还的书
        Book tem = this.books[index];

        //让书数量+1
        tem.incrCount();
        if(index == this.index-1){
            tem = null;
        }else{
            //删除我自己的 列表
            System.arraycopy(books, index + 1, books, index, books.length - index - 1);
        }
        this.index--;

    }

}
